import 'dart:typed_data';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wayofdressing/contraints.dart';
import 'package:wayofdressing/components/myiconbutton.dart';
import 'package:wayofdressing/components/inmenubutton.dart';
import 'package:wayofdressing/dio/configureDio.dart';
import 'package:wayofdressing/screens/about_us_screen.dart';
import 'package:wayofdressing/screens/edit_self_information_screen.dart';
import 'package:image_picker/image_picker.dart';
import 'package:wayofdressing/dio/UserDetailDio.dart';
import 'dart:io';
import 'package:wayofdressing/good_method/decode_base64_to_bytes.dart';
import 'package:wayofdressing/all_widget/head_image.dart';
import 'package:wayofdressing/all_information/user_information.dart';
import 'package:wayofdressing/screens/setting_screen.dart';

class MyScreen extends StatefulWidget {
  static final String id = 'myscreen';

  @override
  State<MyScreen> createState() => _MyScreenState();
}

class _MyScreenState extends State<MyScreen> {
  MenuController menuController = MenuController();
  File? _image;
  Future getImage() async {
    final ImagePicker picker = ImagePicker();
    final XFile? image = await picker.pickImage(source: ImageSource.gallery);

    if (image != null) {
      setState(() {
        _image = File(image.path);
        headImage=FileImage(_image!);
      });
      upgradeImage();
    }
  }

  Future<void> upgradeImage() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    int userId = prefs.getInt('id') ?? 0;

    // 更新用户头像信息
    await updateUserDetailByUserId(
      dio: dio,
      userId: userId,
      imagePath: _image?.path,
    );
    Response response = await getUserDetailByUserId(userId: userId, dio: dio);
    dynamic data = response.data['data'];
    String? base64Image = data['imageBytes'];
    setState(() {
      if (base64Image != null && base64Image.isNotEmpty) {
        Uint8List imageBytes = decodeBase64ToBytes(base64Image);
        headImage = MemoryImage(imageBytes);
      }
    });
  }


  Future getUserInformation() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    userId = prefs.getInt('id') ?? 0;
    name=prefs.getString('username')??'';
    Response response = await getUserDetailByUserId(userId: userId, dio: dio);
    dynamic data = response.data['data'];
    String? base64Image = data['imageBytes'];
    setState(() {
      if (base64Image != null && base64Image.isNotEmpty) {
        prefs.setString(base64Image, 'base64Image');
        Uint8List imageBytes = decodeBase64ToBytes(base64Image);
        headImage = MemoryImage(imageBytes);
      }
      followingCount=data['followingCount']??0;
      followersCount=data['followersCount']??0;
      bio = data['bio'] ?? '';
      gender = data['gender'] ?? '未设置';
      birthday = data['birthday'] ?? '未设置';
      location = data['location'] ?? '未设置';
      school = data['school'] ?? '未设置';
      name = prefs.getString('username') ?? '';
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getUserInformation();
  }
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xfffffaf0),
      appBar: AppBar(
        backgroundColor: Color(0xfffffaf0),
        elevation: 0,
        toolbarHeight: 80,
        leadingWidth: 200,
        actions: [
          MenuAnchor(
            controller: menuController,
            menuChildren: [
              InMenuButton(
                onPressed: () {
                  Navigator.pushNamed(context, AboutUs.id);
                  menuController.close();
                },
                text: '关于我们',
                alignment: Alignment.centerRight,
              ),
              InMenuButton(
                onPressed: () {},
                text: '背景设置',
                alignment: Alignment.centerRight,
              ),
              InMenuButton(
                onPressed: () {},
                text: '联系客服',
                alignment: Alignment.centerRight,
              ),
              InMenuButton(
                onPressed: () {},
                text: '问题咨询',
                alignment: Alignment.centerRight,
              ),
            ],
            style: MenuStyle(
              shape: MaterialStateProperty.all(
                RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(25.0),
                ),
              ),
              alignment: Alignment(-3, 0.5),
              padding: MaterialStateProperty.all(EdgeInsets.all(15.0)),
              shadowColor: MaterialStateProperty.all(Colors.transparent),
              backgroundColor: MaterialStateProperty.all(
                Colors.black.withOpacity(0.4),
              ),
            ),
            builder: (BuildContext context, MenuController controller,
                Widget? child) {
              return GestureDetector(
                onTap: () {
                  if (controller.isOpen) {
                    controller.close();
                  } else {
                    controller.open();
                  }
                },
                child: Icon(
                  Icons.keyboard_control_rounded,
                  size: kAppBarButtonSize,
                  color: Colors.black,
                ),
              );
            },
          ),
          SizedBox(
            width: 20,
          )
        ],
      ),
      endDrawer: const SettingScreen(),
      body: Column(
        children: [
          Expanded(
            child: Container(),
          ),
          Expanded(
            flex: 3,
            child: Stack(
              clipBehavior: Clip.none,
              alignment: Alignment(0, 0),
              children: [
                Container(
                  margin: EdgeInsets.only(left: 30,right:30,bottom: 8),
                  decoration: BoxDecoration(
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(0.2),
                          // 阴影颜色和透明度
                          spreadRadius: 2,
                          // 阴影扩展半径
                          blurRadius: 5,
                          // 阴影模糊半径
                          offset: Offset(0, 5), // 阴影偏移量
                        ),
                      ],
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(25)),
                  child: Column(
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          TextButton(
                            onPressed: () {
                              showModalBottomSheet(
                                  isScrollControlled: true,
                                  context: context,
                                  builder: (context) =>
                                      EditSelfInformation());
                            },
                            child: Text(
                              '编辑',
                              style: TextStyle(
                                color: Colors.black,
                                fontWeight: FontWeight.bold,
                                fontSize: 14,
                              ),
                            ),
                          )
                        ],
                      ),
                      SizedBox(
                        height: 10,
                      ),
                      Expanded(
                        flex: 2,
                        child: Column(
                          children: [
                            Row(
                              mainAxisAlignment:
                                  MainAxisAlignment.center,
                              children: [
                                Flexible(
                                  child: Text(
                                    name,
                                    style: TextStyle(
                                      color: Colors.black,
                                      fontWeight: FontWeight.bold,
                                      fontSize: 24,
                                    ),
                                  ),
                                ),
                              ],
                            ),
                            Row(
                              mainAxisAlignment:
                                  MainAxisAlignment.center,
                              children: [
                                Text(
                                  '关注：$followingCount',
                                  style: TextStyle(
                                    color: Colors.grey[600],
                                    fontSize: 12,
                                  ),
                                ),
                                SizedBox(
                                  width: 8,
                                ),
                                Text(
                                  '粉丝：$followersCount',
                                  style: TextStyle(
                                    color: Colors.grey[600],
                                    fontSize: 12,
                                  ),
                                ),
                              ],
                            ),
                            Row(
                              mainAxisAlignment:
                                  MainAxisAlignment.start,
                              children: [
                                Padding(
                                  padding: const EdgeInsets.symmetric(
                                      horizontal: 24.0),
                                  child: Text(
                                    'ID：$userId',
                                    style: TextStyle(
                                      color: Colors.black,
                                      fontSize: 12,
                                    ),
                                  ),
                                ),
                              ],
                            ),
                            // Row(
                            //   mainAxisAlignment:
                            //       MainAxisAlignment.start,
                            //   children: [
                            //     Padding(
                            //       padding: const EdgeInsets.symmetric(
                            //           horizontal: 24.0),
                            //       child: Text(
                            //         'IP：湖北',
                            //         style: TextStyle(
                            //           color: Colors.black,
                            //           fontSize: 12,
                            //         ),
                            //       ),
                            //     ),
                            //   ],
                            // ),
                          ],
                        ),
                      ),
                      Expanded(
                        flex: 3,
                        child: Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            Container(
                              margin: const EdgeInsets.symmetric(
                                  horizontal: 24.0),
                              child: ConstrainedBox(
                                constraints: BoxConstraints(
                                    maxWidth: MediaQuery.of(context)
                                            .size
                                            .width -
                                        88),
                                child: Text(
                                  '个人简介：$bio',
                                  softWrap: true,
                                  style: TextStyle(
                                    color: Colors.black,
                                    fontSize: 12,
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                      Expanded(
                        flex: 4,
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: [
                            Row(
                              mainAxisAlignment:
                                  MainAxisAlignment.spaceEvenly,
                              children: [
                                myIconButton(
                                  buttonText: '发布',
                                  myIcon: Icon(
                                    Icons.add_circle_outline_rounded,
                                    size: kIconButtonSize,
                                  ),
                                  onPressed: () {
                                  },
                                ),
                                myIconButton(
                                  buttonText: '支付',
                                  myIcon: Icon(
                                    Icons.payment_rounded,
                                    size: kIconButtonSize,
                                  ),
                                  onPressed: () {},
                                ),
                                myIconButton(
                                  buttonText: '收藏',
                                  myIcon: Icon(
                                    Icons.grade_outlined,
                                    size: kIconButtonSize,
                                  ),
                                  onPressed: () {},
                                ),
                                myIconButton(
                                  buttonText: '交易',
                                  myIcon: Icon(
                                    Icons.currency_exchange_rounded,
                                    size: kIconButtonSize,
                                  ),
                                  onPressed: () {},
                                ),
                              ],
                            ),
                            Row(
                              mainAxisAlignment:
                                  MainAxisAlignment.spaceEvenly,
                              children: [
                                myIconButton(
                                  buttonText: '历史',
                                  myIcon: Icon(
                                    Icons.history_rounded,
                                    size: kIconButtonSize,
                                  ),
                                  onPressed: () {},
                                ),
                                myIconButton(
                                  buttonText: '购物车',
                                  myIcon: Icon(
                                    Icons
                                        .local_grocery_store_outlined,
                                    size: kIconButtonSize,
                                  ),
                                  onPressed: () {},
                                ),
                                myIconButton(
                                  buttonText: '橱窗',
                                  myIcon: Icon(
                                    Icons.savings_outlined,
                                    size: kIconButtonSize,
                                  ),
                                  onPressed: () {},
                                ),
                                Builder(
                                  builder: (context)=>myIconButton(
                                    buttonText: '设置',
                                    myIcon: Icon(
                                      Icons.settings_outlined,
                                      size: kIconButtonSize,
                                    ),
                                    onPressed: () {
                                      Scaffold.of(context).openEndDrawer();
                                    },
                                  ),
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
                Positioned(
                  top: -kHeadRadius,
                  child: GestureDetector(
                    onTap: () {
                      getImage();
                    },
                    child: CircleAvatar(
                      backgroundColor: Colors.black,
                      backgroundImage: headImage,
                      radius: kHeadRadius,
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
